using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Web.Configuration;
using System.Security.Principal;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Administration
{
    public class DebugHelpPage : StarznetBaseAdministrationPage
    {
        private SPWebApplication _oWebApp;
        protected CheckBox ChkCallStack;
        protected CheckBox ChkCustomErrors;
        protected CheckBox ChkDebug;
        protected CheckBox ChkLocalOnly;
        protected CheckBox ChkTrace;
        protected CheckBox ChkTracePageOutput;
        protected DropDownList DdTrustLevels;
        protected RadioButton rdoTraceCategory;
        protected RadioButton rdoTraceTime;
        protected WebApplicationSelector Selector;
        private string sOwner = typeof(DebugHelpPage).Name;
        protected InputFormTextBox TxtTraceReqLimit;

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            Collection<SPWebConfigModification> oMods = _oWebApp.WebConfigModifications;
            int iStartCount = oMods.Count;
            for (int i = iStartCount - 1; i >= 0; i--)
            {
                SPWebConfigModification oMod = oMods[i];
                if (oMod.Owner == this.sOwner)
                {
                    oMods.Remove(oMod);
                }
            }

            if (iStartCount > oMods.Count)
            {
                _oWebApp.WebService.ApplyWebConfigModifications();
            }

            SPWebConfigModification oDebugMod = new SPWebConfigModification("debug", "configuration/system.web/compilation");
            oDebugMod.Value = this.ChkDebug.Checked.ToString().ToLower();
            oDebugMod.Owner = sOwner;
            oDebugMod.Sequence = 0;
            oDebugMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
            _oWebApp.WebConfigModifications.Add(oDebugMod);

            SPWebConfigModification oCallStackMod = new SPWebConfigModification("CallStack", "/configuration/SharePoint/SafeMode");
            oCallStackMod.Value = this.ChkCallStack.Checked.ToString().ToLower();
            oCallStackMod.Owner = sOwner;
            oCallStackMod.Sequence = 0;
            oCallStackMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
            _oWebApp.WebConfigModifications.Add(oCallStackMod);

            SPWebConfigModification oTrustMod = new SPWebConfigModification("level", "/configuration/system.web/trust");
            oTrustMod.Value = this.DdTrustLevels.SelectedValue;
            oTrustMod.Owner = sOwner;
            oTrustMod.Sequence = 0;
            oTrustMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
            _oWebApp.WebConfigModifications.Add(oTrustMod);

            SPWebConfigModification oCustomErrMod = new SPWebConfigModification("mode", "configuration/system.web/customErrors");
            oCustomErrMod.Value = this.ChkCustomErrors.Checked ? "On" : "Off";
            oCustomErrMod.Owner = sOwner;
            oCustomErrMod.Sequence = 0;
            oCustomErrMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
            _oWebApp.WebConfigModifications.Add(oCustomErrMod);

            SPWebConfigModification oTraceMod = new SPWebConfigModification("trace", "configuration/system.web");
            string sTraceMode = string.Empty;
            string sLimit = this.TxtTraceReqLimit.Text;
            if (this.rdoTraceTime.Checked)
            {
                sTraceMode = "SortByTime";
            }
            else
            {
                sTraceMode = "SortByCategory";
            }
            oTraceMod.Value = "<trace enabled=\"" + this.ChkTrace.Checked.ToString().ToLower() + "\" traceMode=\"" + sTraceMode + "\" requestLimit=\"" + sLimit + "\" pageOutput=\"" + this.ChkTracePageOutput.Checked.ToString().ToLower() + "\" localOnly=\"" + this.ChkLocalOnly.Checked.ToString().ToLower() + "\"/>";
            oTraceMod.Owner = sOwner;
            oTraceMod.Sequence = 0;
            oTraceMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            _oWebApp.WebConfigModifications.Add(oTraceMod);

            _oWebApp.WebService.Update();
            _oWebApp.WebService.ApplyWebConfigModifications();
        }

        private SPWebApplication GetWebApp()
        {
            return this.Selector.CurrentItem;
        }

        public void OnContextChange(object sender, EventArgs e)
        {
            this._oWebApp = this.GetWebApp();

            IntPtr oUserToken = WindowsIdentity.GetCurrent().Token;
            Configuration oTargetConfig = WebConfigurationManager.OpenWebConfiguration("/", this._oWebApp.Name, "", Environment.MachineName, oUserToken);
            
            CompilationSection oCSection = (CompilationSection)oTargetConfig.GetSection("system.web/compilation");
            this.ChkDebug.Checked = oCSection.Debug;

            TrustSection oTrustSection = (TrustSection)oTargetConfig.GetSection("system.web/trust");
            SecurityPolicySection oSecuritySection = (SecurityPolicySection)oTargetConfig.GetSection("system.web/securityPolicy");
            foreach (TrustLevel oTrust in oSecuritySection.TrustLevels)
            {
                ListItem oItem = new ListItem(oTrust.Name, oTrust.Name);
                if (oTrustSection.Level == oTrust.Name)
                {
                    oItem.Selected = true;
                }
                this.DdTrustLevels.Items.Add(oItem);
            }

            DefaultSection oSafeMode = (DefaultSection)oTargetConfig.GetSection("SharePoint/SafeMode");
            XmlDocument oXdoc = new XmlDocument();
            oXdoc.LoadXml(oSafeMode.SectionInformation.GetRawXml());
            this.ChkCallStack.Checked = bool.Parse(oXdoc.DocumentElement.Attributes["CallStack"].Value);
            CustomErrorsSection oCErrSection = (CustomErrorsSection)oTargetConfig.GetSection("system.web/customErrors");
            switch (oCErrSection.Mode)
            {
                case CustomErrorsMode.RemoteOnly:
                case CustomErrorsMode.On:
                    this.ChkCustomErrors.Checked = true;
                    break;

                case CustomErrorsMode.Off:
                    this.ChkCustomErrors.Checked = false;
                    break;
            }
            TraceSection oTraceSection = (TraceSection)oTargetConfig.GetSection("system.web/trace");
            if (oTraceSection != null)
            {
                this.ChkTrace.Checked = oTraceSection.Enabled;
                this.TxtTraceReqLimit.Text = oTraceSection.RequestLimit.ToString();
                this.ChkTracePageOutput.Checked = oTraceSection.PageOutput;
                this.ChkLocalOnly.Checked = oTraceSection.LocalOnly;
                switch (oTraceSection.TraceMode)
                {
                    case TraceDisplayMode.SortByTime:
                        this.rdoTraceTime.Checked = true;
                        break;

                    case TraceDisplayMode.SortByCategory:
                        this.rdoTraceCategory.Checked = true;
                        break;
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this._oWebApp = this.GetWebApp();
        }
    }
}
